package com.phuoc.activities;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.phuoc.dao.EstablishmentDAO;
import com.phuoc.dao.TypeOfEstablishmentDAO;
import com.phuoc.dao.TypeOfFoodDAO;
import com.phuoc.entities.Establishment;

@TargetApi(9)
public class AddNewActivity extends CustomWindow {

	private ArrayAdapter<String> adapterForTypeOfEstab;
	private ArrayAdapter<String> adapterForTypeOfFood;

	// DAO
	private EstablishmentDAO estabDataSource;
	private TypeOfEstablishmentDAO typeEstabDataSource;
	private TypeOfFoodDAO typeFoodDataSource;

	// layout
	private boolean checkId = false;
	private EditText edtId;
	private EditText edtName;
	private Spinner spinTypeOfEstab;
	private Spinner spinTypeOfFood;
	private EditText edtLocation;
	private Button btnAdd;

	// Dialog
	private Dialog dialogNewTypeOfEstab;
	private Dialog dialogNewTypeOfFood;
	private ProgressDialog dialogWaiting;
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_new);
		this.setWindowTitle("New Establishment");

		// Open database connection
		estabDataSource = new EstablishmentDAO(AddNewActivity.this);
		estabDataSource.open();
		typeEstabDataSource = new TypeOfEstablishmentDAO(this);
		typeEstabDataSource.open();
		typeFoodDataSource = new TypeOfFoodDAO(this);
		typeFoodDataSource.open();

		// Get user information
		edtId = (EditText) findViewById(R.id.edtEstabId);
		edtName = (EditText) findViewById(R.id.edtEstabName);
		spinTypeOfEstab = (Spinner) findViewById(R.id.spinTypeOfEstab);
		spinTypeOfFood = (Spinner) findViewById(R.id.spinTypeOfFood);
		edtLocation = (EditText) findViewById(R.id.edtEstabLocation);
		btnAdd = (Button) findViewById(R.id.btnAdd);

		// Dialog
		dialogNewTypeOfEstab = new Dialog(this);
		dialogNewTypeOfEstab.setContentView(R.layout.new_type);
		dialogNewTypeOfFood = new Dialog(this);
		dialogNewTypeOfFood.setContentView(R.layout.new_type);
		handler = new Handler();

		// Add data to spinner type of establishment
		addDataToSpinnTypeOfEstab();

		// Add data to spinner type of food
		addDataToSpinnTypeOfFood();

		// Event EditText Changed
		EventEditTextTextChanged();

		// Event Add New Type Of Establishment
		addNewTypeOfEstabEvent();

		// Event Add New Type Of Food
		addNewTypeOfFoodEvent();

		// Event Cancel Dialog
		cancleDialogEvent();
	}

	@Override
	protected void onResume() {
		estabDataSource.open();
		typeEstabDataSource.open();
		typeFoodDataSource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		estabDataSource.close();
		typeEstabDataSource.close();
		typeFoodDataSource.close();
		super.onPause();
	}

	private void addDataToSpinnTypeOfEstab() {
		ArrayList<String> listTypeEstablishment = typeEstabDataSource
				.getAllTypeOfEstablishs();
		adapterForTypeOfEstab = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, listTypeEstablishment);
		adapterForTypeOfEstab
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinTypeOfEstab.setAdapter(adapterForTypeOfEstab);
	}

	private void addDataToSpinnTypeOfFood() {
		ArrayList<String> listTypeFood = typeFoodDataSource.getAllTypeOfFood();
		adapterForTypeOfFood = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, listTypeFood);
		adapterForTypeOfFood
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinTypeOfFood.setAdapter(adapterForTypeOfFood);
	}

	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.btnAdd:
			dialogWaiting = ProgressDialog.show(this, "Loading",
					"Adding new establishment");

			Thread th = new Thread(new Runnable() {
				public void run() {
					// Establishment
					String id = edtId.getText().toString();
					String name = edtName.getText().toString();
					long idTypeOfEstab = typeEstabDataSource
							.getIdByName((String) spinTypeOfEstab
									.getSelectedItem());
					long idTypeOfFood = typeFoodDataSource
							.getIdByName((String) spinTypeOfFood
									.getSelectedItem());
					String location = edtLocation.getText().toString();

					Establishment estab1 = new Establishment(id, name,
							idTypeOfEstab, idTypeOfFood, location);
					final boolean result = estabDataSource
							.createEstablishment(estab1);
					handler.post(new Runnable() {
						public void run() {
							if (result) {
								Toast.makeText(getApplicationContext(),
										"Add new establishment",
										Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(getApplicationContext(),
										"Add new establishment",
										Toast.LENGTH_SHORT).show();
							}

							// Return to list of establishment
							AddNewActivity.this.finish();
						}
					});
					// Close Dialog
					dialogWaiting.dismiss();
				}
			});
			th.start();
			break;

		case R.id.btnCancel:
			this.finish();
			break;

		case R.id.btnNewTypeOfEstab:
			dialogNewTypeOfEstab.setTitle("New Type Of Establishment");
			dialogNewTypeOfEstab.show();
			break;

		case R.id.btnNewTypeOfFood:
			dialogNewTypeOfFood.setTitle("New Type Of Food");
			dialogNewTypeOfFood.show();
			break;
		default:
			break;
		}

	}

	private void addNewTypeOfEstabEvent() {
		Button btnNew = (Button) dialogNewTypeOfEstab.findViewById(R.id.btnNew);
		final EditText edtNew = (EditText) dialogNewTypeOfEstab
				.findViewById(R.id.edtNewType);

		btnNew.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				String typeOfEstab = edtNew.getText().toString();
				edtNew.setText("");
				if (!typeOfEstab.isEmpty()
						&& !typeEstabDataSource.checkNameExists(typeOfEstab)) {
					typeEstabDataSource.createTypeOfEstablishment(typeOfEstab);
					adapterForTypeOfEstab.add(typeOfEstab);
					spinTypeOfEstab.setSelection(adapterForTypeOfEstab
							.getPosition(typeOfEstab));
					dialogNewTypeOfEstab.dismiss();
				} else {
					dialogNewTypeOfEstab.dismiss();
				}
			}
		});
	}

	private void addNewTypeOfFoodEvent() {
		Button btnNew = (Button) dialogNewTypeOfFood.findViewById(R.id.btnNew);
		final EditText edtNew = (EditText) dialogNewTypeOfFood
				.findViewById(R.id.edtNewType);

		btnNew.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				String typeOfFood = edtNew.getText().toString();
				edtNew.setText("");
				if (!typeOfFood.isEmpty()
						&& !typeFoodDataSource.checkNameExists(typeOfFood)) {
					typeFoodDataSource.createTypeOfFood(typeOfFood);
					adapterForTypeOfFood.add(typeOfFood);
					spinTypeOfFood.setSelection(adapterForTypeOfFood
							.getPosition(typeOfFood));
					dialogNewTypeOfFood.dismiss();
				} else {
					dialogNewTypeOfFood.dismiss();
				}
			}
		});
	}

	private void cancleDialogEvent() {
		// Button Cancel Dialog New Type Of Estab
		Button btnCancelTypeEstab = (Button) dialogNewTypeOfEstab
				.findViewById(R.id.btnCancel);

		btnCancelTypeEstab.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				dialogNewTypeOfEstab.dismiss();
			}
		});

		// Button Cancel Dialog New Type Of Food
		Button btnCancelTypeFood = (Button) dialogNewTypeOfFood
				.findViewById(R.id.btnCancel);

		btnCancelTypeFood.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				dialogNewTypeOfFood.dismiss();
			}
		});
	}

	@TargetApi(9)
	private void EventEditTextTextChanged() {

		// EditText Id Establishment
		edtId.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				TextView errorView = (TextView) findViewById(R.id.txtErrorId);
				if (s.toString().isEmpty()) {
					errorView.setText("*Pleased enter Id establishment");
					errorView.setVisibility(TextView.VISIBLE);
					checkId = false;

				} else if (estabDataSource.checkIdExists(s.toString())) {
					errorView.setText("*This id is exists.");
					errorView.setVisibility(TextView.VISIBLE);
					checkId = false;
				} else {
					errorView.setText("");
					errorView.setVisibility(TextView.GONE);
					checkId = true;
				}
				btnAdd.setEnabled(false);
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

		// EditText id Filter
		InputFilter filter = new InputFilter() {
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {
				for (int i = start; i < end; i++) {
					if (!Character.isLetterOrDigit(source.charAt(i))
							&& !Character.isSpace(source.charAt(i))) {
						return "";
					}
				}
				return null;
			}
		};
		edtId.setFilters(new InputFilter[] { filter });

		// EditText Name Establishment
		edtName.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable s) {
				TextView errorView = (TextView) findViewById(R.id.txtErrorName);
				if (s.toString().isEmpty()) {
					errorView.setText("*Pleased enter Name establishment");
					errorView.setVisibility(TextView.VISIBLE);
					btnAdd.setEnabled(false);
				} else {
					errorView.setText("");
					errorView.setVisibility(TextView.GONE);

					if (checkId) {
						btnAdd.setEnabled(true);
					} else {
						btnAdd.setEnabled(false);
					}
				}
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
		});

		// EditText name Filter
		edtName.setFilters(new InputFilter[] { filter });
	}
}
